package com.hinnotek.amoeba.ui.activity.old

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import com.google.gson.Gson
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.*
import com.hinnotek.amoeba.databinding.ActivitySellProjectRequirementAddBinding
import com.hinnotek.amoeba.databinding.IncludeSellPurchaseRequestAddLayoutBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.ext.productArray
import com.hinnotek.amoeba.utilities.ClickUtil
import com.lee.common.utils.SharedPreUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.viewmodels.AmibaViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.hinnotek.amoeba.widget.EditSpinnerC
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SellProjectRequirementsAddActivity :
    BaseActivity<ActivitySellProjectRequirementAddBinding>() {
    private var sellPurchaseRequistionDetailBean: SellPurchaseRequistionDetailBean? = null

    val viewModel by viewModels<AmibaViewModel>()
    val publicViewModel by viewModels<PublicInterfaceViewModel>()

    private var purchaseAddData: PurchaseAddBeanTo? = null
    private var purchase_type_to: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("项目需料")

        setContentView(R.layout.activity_sell_project_requirement_add)
    }

    override fun initVew() {

        bindingView.rbAddProduct.setOnClickListener { v: View? ->
            val viewSellProject =
                DataBindingUtil.inflate<IncludeSellPurchaseRequestAddLayoutBinding>(
                    layoutInflater,
                    R.layout.include_sell_purchase_request_add_layout,
                    bindingView.llProjectList,
                    false
                )


            bindingView.llProjectList.addView(viewSellProject.root)

            getListData()

            viewSellProject.tvDel
                .setOnClickListener { v1: View? ->
                    bindingView.llProjectList.removeView(viewSellProject.root)
                }
        }

        bindingView.superButtonAdd.setOnClickListener(View.OnClickListener { v: View? ->
            if (ClickUtil.isFastClick()) {
                return@OnClickListener
            }
            val projectRequirementsJsonBean = mutableListOf<ProjectRequirementsJsonBean>()
            val escDeviceNameS: String =
                bindingView.escDeviceName.editText.getText().toString().trim()
            if (StringUtils.isEmpty(escDeviceNameS)) {
                ToastUtils.show(mContext, "请选择产品名称")
                return@OnClickListener
            }
            val esc_specification_model_s: String =
                bindingView.escSpecificationModel.editText.getText().toString().trim()
            if (StringUtils.isEmpty(esc_specification_model_s)) {
                ToastUtils.show(mContext, "请选择规格型号")
                return@OnClickListener
            }
            val tvMoneyS: String = bindingView.tvMoney.text.toString()
            val productNum: String = bindingView.edQuantityToBePurchased.text.toString().trim()
            if (StringUtils.isEmpty(productNum)) {
                ToastUtils.show(mContext, "请填写采购数量")
                return@OnClickListener
            }
            projectRequirementsJsonBean.add(
                ProjectRequirementsJsonBean(
                    escDeviceNameS,
                    esc_specification_model_s,
                    tvMoneyS,
                    productNum
                )
            )
            for (i in 0 until bindingView.llProjectList.getChildCount()) {
                val layout: View = bindingView.llProjectList.getChildAt(i)
                val escDeviceNameV: EditSpinnerC = layout.findViewById(R.id.esc_device_name)
                val escSpecificationModelV: EditSpinnerC =
                    layout.findViewById(R.id.esc_specification_model)
                val tv_money_v: TextView = layout.findViewById(R.id.tv_money)
                val edQuantityToBePurchasedV: EditText =
                    layout.findViewById(R.id.ed_quantity_to_be_purchased)
                val esc_device_name_v_s: String =
                    escDeviceNameV.editText.text.toString().trim()
                if (StringUtils.isEmpty(esc_device_name_v_s)) {
                    ToastUtils.show(mContext, "请选择产品名称")
                    return@OnClickListener
                }
                val escSpecificationModelVS: String =
                    escSpecificationModelV.editText.text.toString().trim()
                if (StringUtils.isEmpty(escSpecificationModelVS)) {
                    ToastUtils.show(mContext, "请选择规格型号")
                    return@OnClickListener
                }
                val tv_money_v_s: String = tv_money_v.text.toString()
                val edQuantityToBePurchasedVS: String =
                    edQuantityToBePurchasedV.getText().toString().trim()
                if (StringUtils.isEmpty(edQuantityToBePurchasedVS)) {
                    ToastUtils.show(mContext, "请填写采购数量")
                    return@OnClickListener
                }
                projectRequirementsJsonBean.add(
                    ProjectRequirementsJsonBean(
                        esc_device_name_v_s,
                        escSpecificationModelVS,
                        tv_money_v_s,
                        edQuantityToBePurchasedVS
                    )
                )
            }
            val met_note_s: String = bindingView.metNote.getContentText().trim()
            if (StringUtils.isEmpty(met_note_s)) {
                ToastUtils.show(mContext, "请填写备注")
                return@OnClickListener
            }
            val projectRequirementsJson: String = Gson().toJson(projectRequirementsJsonBean)
            if (sellPurchaseRequistionDetailBean != null) {
                updateAmibaPurchaseProject(
                    sellPurchaseRequistionDetailBean!!.amibaPurchaseId,
                    met_note_s,
                    projectRequirementsJson
                )
            } else {
                purchaseAddData?.let {
                    addAmibaPurchaseSale(
                        it.customerId,
                        it.customerName,
                        it.amibaCustomerProjectId,
                        it.projectName,
                        it.amibaProjectId,
                        it.provideProjectName,
                        it.applicationMethod,
                        it.deliveryDate,
                        it.projectOverview,
                        it.technicalRequirement,
                        met_note_s,
                        it.approvalUserId,
                        it.approvalUser,
                        it.sendUserId,
                        it.sendUser,
                        projectRequirementsJson
                    )
                }

            }
        })
    }

    override fun setData() {
        sellPurchaseRequistionDetailBean = intent.getSerializableExtra("detail") as SellPurchaseRequistionDetailBean?
        purchaseAddData = intent.getSerializableExtra("purchaseAddBeanTo") as PurchaseAddBeanTo?
        purchase_type_to = intent.getStringExtra("purchase_type_to")

        getListData()

        if (sellPurchaseRequistionDetailBean != null) {

            bindingView.metNote.contentText = sellPurchaseRequistionDetailBean?.projectRemarks
            for (i in sellPurchaseRequistionDetailBean!!.amibaPurchaseProjects.indices) {
                val amibaPurchaseProjects: AmibaPurchaseProjects =
                    sellPurchaseRequistionDetailBean!!.amibaPurchaseProjects.get(i)
                if (i == 0) {
                    bindingView.escDeviceName.setText(amibaPurchaseProjects.productName)
                    bindingView.escSpecificationModel.setText(amibaPurchaseProjects.productTypeName)
                    bindingView.tvMoney.text = amibaPurchaseProjects.productTypePrice
                    bindingView.edQuantityToBePurchased.setText(amibaPurchaseProjects.productNum.toString())
                } else {
                    val viewSellProject: View = LayoutInflater.from(mContext).inflate(
                        R.layout.include_sell_purchase_request_add_layout,
                        bindingView.llProjectList,
                        false
                    )
                    bindingView.llProjectList.addView(viewSellProject)
                    val escDeviceNameV: EditSpinnerC =
                        viewSellProject.findViewById(R.id.esc_device_name)
                    val editSpinnerC: EditSpinnerC =
                        viewSellProject.findViewById(R.id.esc_specification_model)
                    val tv_money_v: TextView = viewSellProject.findViewById(R.id.tv_money)
                    val edQuantityToBePurchasedV: EditText =
                        viewSellProject.findViewById(R.id.ed_quantity_to_be_purchased)
                    escDeviceNameV.setText(amibaPurchaseProjects.productName)
                    editSpinnerC.setText(amibaPurchaseProjects.productTypeName)
                    tv_money_v.text = amibaPurchaseProjects.productTypePrice
                    edQuantityToBePurchasedV.setText(amibaPurchaseProjects.productNum.toString())
                    viewSellProject.findViewById<View>(R.id.tv_del)
                        .setOnClickListener { v1: View? ->
                            bindingView.llProjectList.removeView(viewSellProject)
                        }
                }
            }
        }
    }

    private fun getListData() {
        publicViewModel.getProductList()
            .observe(this, object : ObserverState<MutableList<ProductListBean>>() {
                override fun onDataChange(data: MutableList<ProductListBean>) {
                    var productId = 0
                    bindingView.escDeviceName.initAdapter(productArray(data))
                    bindingView.escDeviceName.setOnItemClickListener { parent, view, position, id ->
                        productId = data[position].productId
                    }
                    publicViewModel.getProductTypeListByProductId(productId)
                        .observe(this@SellProjectRequirementsAddActivity,
                            object : ObserverState<MutableList<ProductManagamentBean>>() {
                                override fun onDataChange(data: MutableList<ProductManagamentBean>) {
                                    val strings = arrayOfNulls<String>(data.size).apply {
                                        for (index in data.indices) {
                                            this[index] = data[index].productTypeName
                                        }
                                    }
                                    bindingView.escSpecificationModel.initAdapter(strings)
                                    bindingView.escSpecificationModel.setOnItemClickListener { parent, view, position, id ->
                                        val bean = data[position]
                                        val productTypePrice: String = bean.productPrice
                                        bindingView.tvMoney.setText(productTypePrice)
                                    }
                                    super.onDataChange(data)
                                }
                            })
                    super.onDataChange(data)
                }
            })
    }

    /**
     * app端添加销售采购申请接口
     */
    private fun addAmibaPurchaseSale(
        customerId: Int,
        customerName: String,
        amibaCustomerProjectId: Int,
        projectName: String,
        amibaProjectId: Int,
        provideProjectName: String,
        applicationMethod: Int,
        deliveryDate: String,
        projectOverview: String,
        technicalRequirement: String,
        projectRemarks: String,
        approvalUserId: Int,
        approvalUser: String,
        sendUserId: Int,
        sendUser: String,
        amibaPurchaseProjectJson: String
    ) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val map = mutableMapOf<String, Any>().apply {
            put("applyUserId", SharedPreUtils.getInteger("userId", 0))
            put("orgId", SharedPreUtils.getInteger("orgId", 0))
            put("orgName", SharedPreUtils.getString("orgName"))
            if (purchase_type_to == "market" || purchase_type_to == "technology") {
                put("customerId", customerId)
                put("customerName", customerName)
                put("amibaCustomerProjectId", amibaCustomerProjectId)
                put("projectName", projectName)
            } else if (purchase_type_to == "rD") {
                put("amibaProjectId", amibaProjectId)
                put("provideProjectName", provideProjectName)
            }
            put("applicationMethod", applicationMethod)
            put("deliveryDate", deliveryDate)
            put("projectOverview", projectOverview)
            put("technicalRequirement", technicalRequirement)
            put("projectRemarks", projectRemarks)
            put("approvalUserId", approvalUserId)
            put("approvalUser", approvalUser)
            put("sendUserId", sendUserId)
            put("sendUser", sendUser)
            put("amibaPurchaseProjectJson", amibaPurchaseProjectJson)
            put("createUser", SharedPreUtils.getString("personName"))
        }

        if (purchase_type_to == "market") {
            viewModel.addAmibaPurchaseSale(getRequestBody(map))
                .observe(this, object : ObserverState<BaseBean>() {
                    override fun onDataChange(data: BaseBean) {
                        customDialog.dismiss()
                        super.onDataChange(data)
                    }

                    override fun onError(msg: String?, code: Int) {
                        customDialog.dismiss()
                        ToastUtils.showShort(mContext, msg)
                        super.onError(msg, code)
                    }
                })
        } else if (purchase_type_to == "technology") {
            viewModel.addAmibaPurchaseTechnology(getRequestBody(map))
                .observe(this, object : ObserverState<BaseBean>() {
                    override fun onDataChange(data: BaseBean) {
                        customDialog.dismiss()
                        super.onDataChange(data)
                    }

                    override fun onError(msg: String?, code: Int) {
                        customDialog.dismiss()
                        ToastUtils.showShort(mContext, msg)
                        super.onError(msg, code)
                    }
                })
        } else if (purchase_type_to == "rD") {
            viewModel.addAmibaPurchaseDevelop(getRequestBody(map))
                .observe(this, object : ObserverState<BaseBean>() {
                    override fun onDataChange(data: BaseBean) {
                        customDialog.dismiss()
                        super.onDataChange(data)
                    }

                    override fun onError(msg: String?, code: Int) {
                        customDialog.dismiss()
                        ToastUtils.showShort(mContext, msg)
                        super.onError(msg, code)
                    }
                })
        }
    }

    /**
     * app端修改项目需料接口
     */
    private fun updateAmibaPurchaseProject(
        amibaPurchaseId: Int,
        projectRemarks: String,
        amibaPurchaseProjectJson: String
    ) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val map = mutableMapOf<String,Any>().apply {
           put("amibaPurchaseId", amibaPurchaseId)
           put("projectRemarks", projectRemarks)
           put("amibaPurchaseProjectJson", amibaPurchaseProjectJson)
        }
        viewModel.updateAmibaPurchaseProject(getRequestBody(map)).observe(this,object :ObserverState<BaseBean>(){
            override fun onDataChange(data: BaseBean) {
                customDialog.dismiss()
                finishActivity()
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })
    }
}